package com.example.word.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class ImageCompressor {

    // 压缩图片方法
    public static File compressImage(Context context, Uri imageUri, int maxSizeKB) {
        try {
            // 从Uri获取输入流
            InputStream inputStream = context.getContentResolver().openInputStream(imageUri);

            // 解码输入流为位图
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

            // 计算压缩比例
            int quality = 100;
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
            while (stream.toByteArray().length / 1024 > maxSizeKB) {
                stream.reset();
                quality -= 10;
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
            }

            // 将压缩后的位图保存到文件
            File compressedFile = new File(context.getCacheDir(), "word-image-" + UUID.randomUUID().toString().replace("-", "") + ".jpg");
            FileOutputStream fos = new FileOutputStream(compressedFile);
            fos.write(stream.toByteArray());
            fos.flush();
            fos.close();

            return compressedFile;
        } catch (IOException e) {
            Log.e("ImageCompressor", "IOException during image compression: " + e.getMessage());
            return null;
        }
    }
}
